import axios from 'axios'
import { Message } from 'element-ui'
import { getRealToken } from './util'

// create an axios instance
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? window.webConfig.webApiBaseUrl
      : process.env.VUE_APP_BASE_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (process.env.NODE_ENV === 'staging') {
      if(config.url.includes('getUserInfo') || config.url.includes('users/self')){
        config.baseURL = 'http://10.223.1.5:8080'
      }
    }
    const accessObj = getRealToken()
    const frontTokenKey = accessObj?.insightToken
    const isCheckOut = accessObj?.isCheckOut

    if (!frontTokenKey) {
      config.headers = {
        // Authorization: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6Z3MiLCJ0ZW5hbnRJZCI6Ii0xIiwiZXhwIjoxNzMyODY5MTMyLCJpYXQiOjE3MzI3ODI3MzJ9.upAsGQKY3Q9ofZ1X5zOx4Rln6gMSLmG_GFXYoUB0REV-_l8s14ItwFN57-nV_f70e4irycWmrtFuydF-8GO1Jw',
        isCheckOut: isCheckOut ? 'true' : 'false',
        ...config.headers
      }
      return config
    } else {
      config.headers = {
        Authorization: frontTokenKey,
        isCheckOut: isCheckOut ? 'true' : 'false',
        ...config.headers
      }
      return config
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */
  (response) => {
    const res = response.data
    return res
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
